import os

from django.conf import settings
from django.core.checks import Warning, Error

from utils.oss.pyrados import HarborObject


def check_ceph_settings(**kwargs):
    errors = []
    cephs = getattr(settings, 'CEPH_RADOS', None)
    if not cephs:
        errors.append(Warning('未配置CEPH集群信息，配置文件中配置“CEPH_RADOS”', hint='CEPH_RADOS'))

    if 'default' not in cephs:
        errors.append(Warning('配置文件中CEPH集群信息配置“CEPH_RADOS”中必须存在一个别名“default”', hint='CEPH_RADOS.default'))

    enable_choices = []
    for using in cephs:
        if len(using) >= 16:
            errors.append(Warning(f'CEPH集群配置“CEPH_RADOS”中，别名"{using}"太长，不能超过16字符'))

        # 检查 多部分上传
        s3_multipart_pool_name = settings.MULTIPART_POOL_CONF
        if not s3_multipart_pool_name.get(using):
            errors.append(Error(f'S3多部分上传MULTIPART_POOL_CONF配置中缺少对应集群别名配置:{using}。'))

        if not s3_multipart_pool_name[using].get('MULTIPART_POOL_NAME'):
            errors.append(Error(f'S3多部分上传MULTIPART_POOL_CONF中别名{using}没有MULTIPART_POOL_NAME的配置。'))

        ceph = cephs[using]
        conf_file = ceph['CONF_FILE_PATH']
        if not os.path.exists(conf_file):
            errors.append(Warning(f'别名为“{using}”的CEPH集群配置文件“{conf_file}”不存在'))

        keyring_file = ceph['KEYRING_FILE_PATH']
        if not os.path.exists(keyring_file):
            errors.append(Warning(f'别名为“{using}”的CEPH集群keyring配置文件“{keyring_file}”不存在'))

        if 'USER_NAME' not in ceph:
            errors.append(Warning(f'别名为“{using}”的CEPH集群配置信息未设置“USER_NAME”'))

        if 'POOL_NAME' not in ceph:
            errors.append(Warning(f'别名为“{using}”的CEPH集群配置信息未设置“POOL_NAME”'))

        if not (isinstance(ceph['POOL_NAME'], str) or isinstance(ceph['POOL_NAME'], tuple)):
            errors.append(Warning(f'别名为“{using}”的CEPH集群配置信息“POOL_NAME”必须是str或者tuple'))

        if s3_multipart_pool_name[using].get('MULTIPART_POOL_NAME') in ceph['POOL_NAME']:
            errors.append(Error('S3多部分上传MULTIPART_POOL_CONF配置中存储池不可与对象存储（iharbor）中使用的存储池混用。'))

        ho = HarborObject(pool_name='', obj_id='', obj_size=2, cluster_name=ceph['CLUSTER_NAME'],
                          user_name=ceph['USER_NAME'], conf_file=conf_file,
                          keyring_file=keyring_file)

        try:
            list_pool_name = ho.rados.get_cluster().list_pools()
            # 配置的存储池不在集群所创建的所有存储池中。
            if s3_multipart_pool_name[using].get('MULTIPART_POOL_NAME') not in list_pool_name:
                errors.append(Error(f's3多部分上传MULTIPART_POOL_CONF配置中别名{using}配置的存储池不存于在该集群中。'))
        except Error as exe:
            return exe
        except Exception as e:
            return errors.append(Error(f'无法连接ceph，别名为“{using}”的CEPH集群连接错误:{str(e)}'))

        if ('DISABLE_CHOICE' in ceph) and (ceph['DISABLE_CHOICE'] is True):
            continue

        enable_choices.append(using)

    if not enable_choices:
        errors.append(Warning('没有可供选择的CEPH集群配置，创建bucket时没有可供选择的CEPH集群，'
                              '请至少确保有一个CEPH集群配置“DISABLE_CHOICE”为False'))

    return errors
